package cn.org.timespace.ons.inside.mina.server;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import cn.org.timespace.ons.inside.common.SocketInPropertie;
import cn.org.timespace.ons.inside.mina.filter.ESInProtocolCodecFactory;

public class MinaESInServer {

	private final static Log log = LogFactory.getLog(MinaESInServer.class);
	
	private final static int port = Integer.parseInt(SocketInPropertie.getProperty("in_socket.server.port", "8889"));
	private final static String codecFilterName = SocketInPropertie.getProperty("mina.codecfilter.name", "ESinFilter");
	
	private static IoAcceptor acceptor;
	
	public final static void run() {
		try {
			log.debug("MinaESCardServer监听启动开始...");
			acceptor = new NioSocketAcceptor();

			DefaultIoFilterChainBuilder filterChainBuilder = acceptor.getFilterChain();
			
			//指定编码过滤器
			filterChainBuilder.addLast(codecFilterName, new ProtocolCodecFilter(new ESInProtocolCodecFactory(Charset.defaultCharset())));
			
			//建立无界的线程池
			//Executor threadPool = Executors.newCachedThreadPool();
			Executor threadPool = Executors.newFixedThreadPool(2000);
			filterChainBuilder.addLast("threadPool", new ExecutorFilter(threadPool));
			
			//指定业务逻辑处理器
			acceptor.setHandler(new ESInServerHandler());
			
			//空闲等待时间(5分钟)
			acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 300);   
			
			//设置端口号,并启动监听 
			acceptor.bind(new InetSocketAddress(port));
			log.debug("MinaESCardServer监听启动成功，端口号为：" + port);
		} catch (Exception e) {
			log.error("启动中出现异常：" + e);
			e.printStackTrace();
		}
	}
	
	/**
	 * 获得客户端连接总数
	 * @return
	 */
	public static int getConNum(){
		
		int num = acceptor.getManagedSessionCount();
		log.debug("客户端连接总数:" + num);
		
		return num;
	}
	
	/**
	 * 向每个客户端发送消息
	 * @return
	 */
	public static void sendConMessage(){
		
		IoSession session;
		
		Map<Long, IoSession> conMap = acceptor.getManagedSessions();
		
		Iterator<Long> iter = conMap.keySet().iterator();
		while (iter.hasNext()) {
			Long key = iter.next();
			session = (IoSession)conMap.get(key);
			session.write("" + key.toString());
		}
	}
	
	public static void main(String[] args) {
		MinaESInServer.run();
	}

	public static IoAcceptor getAcceptor() {
		return acceptor;
	}

}
